package org.dragon.controllers;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.dragon.commons.Const;
import org.dragon.commons.JsonResult;
import org.dragon.commons.Permit;
import org.dragon.models.Permission;
import org.dragon.services.PermissionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/24 9:13
 */
@RestController
@RequestMapping("/permission")
@Validated
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    @Permit(roles = Const.ROOT)
    @GetMapping("/")
    public Object list() {
        return permissionService.selectAll();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Permit(roles = Const.ROOT)
    @PostMapping("/")
    public Object add(@RequestBody @Valid Permission permission) {
        permission.setId(null);
        permissionService.save(permission);
        return JsonResult.ok();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Permit(roles = Const.ROOT)
    @PutMapping("/{id}")
    public Object update(@PathVariable Long id, @RequestBody @Valid Permission permission) {
        permission.setId(id);
        permissionService.save(permission);
        return JsonResult.ok();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Permit(roles = Const.ROOT)
    @DeleteMapping("/{id}")
    public Object del(@PathVariable Long id) {
        permissionService.delete(id);
        return JsonResult.ok();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Permit(roles = Const.ROOT)
    @DeleteMapping("/")
    public Object clear() {
        permissionService.clear();
        return JsonResult.ok();
    }
}
